<?php
namespace Backend\Models\Sys;

use Backend\Models\Base;

class Role extends Base
{

    public function initialize()
    {
        parent::initialize();
    }

    public function getSource()
    {
        return 'sys_user_role';
    }

    public function isExists($name)
    {
        try {
            $ret = $this->db()->query('SELECT count(*) AS `cnt` FROM `sys_user_role` WHERE `name`=:name LIMIT 1', [
                'name' => $name,
            ])->fetch();
            if ($ret !== false && isset($ret['cnt'])) {
                return $ret['cnt'] > 0;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('SELECT', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return -500;
    }

    public function gets($status = '')
    {
        try {
            $query = $this->queryBuilder()->columns('*')->from(self::class);
            if ($status == 'valid') {
                $query->where('status=:status:', ['status' => 1]);
            } else {
                if ($status == 'invalid') {
                    $query->where('status=:status:', ['status' => 0]);
                }
            }
            $result = $query->getQuery()->execute()->toArray();
            if ($result !== false && is_array($result)) {
                return $result;
            }
        } catch (\Exception $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function get($id)
    {
        try {
            $ret = $this->db()->query('SELECT * FROM `sys_user_role` WHERE `id`=:id LIMIT 1', ['id' => $id])->fetch();
            if ($ret !== false) {
                return $ret;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('SELECT', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function add($entity)
    {
        try {
            if ($this->db()->insertAsDict('sys_user_role', $entity)) {
                return $this->db()->lastInsertId();
            }
        } catch (\PDOException $ex) {
            $this->errorLog('INSERT', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function edit($entity)
    {
        try {
            return $this->db()->updateAsDict('sys_user_role', $entity, sprintf('id=%d LIMIT 1', intval($entity['id'])));
        } catch (\PDOException $ex) {
            $this->errorLog('UPDATE', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
            return false;
        }
    }
}
